"""
    Author:
    Date: 2018-12-29

    API接口调用
"""

import random
from django.conf import settings

from .. import helpers
from .. import usecases
from .. helpers import gma_login_required
from entities import app_mgr
from entities import banner_mgr
from entities import call_mgr
from entities import complaint_mgr
from entities import jpush_mgr
from entities import gift_mgr
from entities import gm_mgr
from entities import guild_mgr
from entities import message_mgr
from entities import moment_mgr
from entities import photo_mgr
from entities import profile_mgr
from entities import radio_mgr
from entities import sms_mgr
from entities import user_mgr
from entities import vchat_api_mgr
from entities import video_mgr
from entities.consts import *
from entities.err import *

from utils import ajax
from utils import qiniu_util
from utils import util
from utils.log import Log


@gma_login_required
def api_add_diamond(request):
    """ 增加用户钻石 """
    uid = request.POST['uid'].strip()
    amount = request.POST['amount'].strip()

    openid = helpers.get_request_openid(request)
    result = vchat_api_mgr.add_user_diamond(uid, amount, openid, '赠送主播')
    Log.info(f'Request api_add_diamond result: {result}')
    return ajax.success_response()


@gma_login_required
def api_set_gm_permission(request):
    """ 设置GM的某个权限 """
    uid = int(request.POST['uid'].strip())
    pid = int(request.POST['pid'].strip())

    gm = gm_mgr.get_gm_detail(uid)
    nickname = gm['nickname']
    new_permission = gm['permission'] | (1 << pid - 1)
    permission_name = gm_mgr.get_gm_permission_name(pid)

    success = gm_mgr.set_gm_permission(uid, new_permission)
    if not success:
        Log.error(f'Set gm permission failed: uid={uid}, pid={pid}, admin={request.user.username}')
        return ajax.error_response(f'开启{permission_name}权限失败!')

    Log.info(f'Set gm permission ok: uid={uid}, pid={pid}, admin={request.user.username}')
    return ajax.success_response()


@gma_login_required
def api_unset_gm_permission(request):
    """ 取消GM的某个权限 """
    uid = int(request.POST['uid'].strip())
    pid = int(request.POST['pid'].strip())

    gm = gm_mgr.get_gm_detail(uid)
    nickname = gm['nickname']
    new_permission = gm['permission'] & ~(1 << pid - 1)
    permission_name = gm_mgr.get_gm_permission_name(pid)

    success = gm_mgr.set_gm_permission(uid, new_permission)
    if not success:
        Log.error(f'Unset gm permission failed: uid={uid}, pid={pid}, admin={request.user.username}')
        return ajax.error_response(f'关闭{permission_name}权限失败!')

    Log.info(f'Unset gm permission ok: uid={uid}, pid={pid}, admin={request.user.username}')
    return ajax.success_response()


@gma_login_required
def api_set_user_is_busy(request):
    """ 设置主播是否处于勿扰模式 """
    uid = int(request.POST['uid'].strip())
    is_busy = int(request.POST['is_busy'].strip())

    result = vchat_api_mgr.set_user_is_busy(uid, is_busy)
    Log.info(f'Request api result: {result}')

    if is_busy == 1:
        vchat_api_mgr.send_hx_message(uid, "管理员为您开启了勿扰模式！")
    else:
        vchat_api_mgr.send_hx_message(uid, "管理员取消了您的勿扰模式！")
    return ajax.success_response()


@gma_login_required
def api_set_user_allow_free_chat(request):
    """ 设置主播是否开启免费通话模式 """
    uid = int(request.POST['uid'].strip())
    allowed = int(request.POST['allowed'].strip())

    user_mgr.update_allow_free_chat_by_uid(uid, allowed)

    if allowed == 1:
        vchat_api_mgr.send_hx_message(uid, "管理员为您开启了新用户上线推送功能！")
    else:
        vchat_api_mgr.send_hx_message(uid, "管理员为您关闭了新用户上线推送功能！")
    return ajax.success_response()


@gma_login_required
def api_recommend_user(request):
    """ 推荐主播 """
    uid = int(request.POST['uid'].strip())
    offset = int(request.POST['offset'].strip())

    user = user_mgr.get_user_detail(uid)
    if user is None:
        return ajax.error_response('用户不存在！')

    current_recommend_value = user['recommend_value']

    if offset == 0:
        # 排名置顶
        max_recommend_value = user_mgr.get_max_recommend_value()
        if max_recommend_value == 0:
            recommend_value = 1000000
        else:
            recommend_value = max_recommend_value + 1
        user_mgr.update_broadcaster_recommend_value_by_uid(uid, recommend_value)
    elif offset == 1:
        # 排名加1
        if current_recommend_value == 0:
            # 加入到推荐位的最后
            min_recommend_value = user_mgr.get_min_recommend_value()
            if min_recommend_value == 0:
                recommend_value = 1000000
            else:
                recommend_value = max(1, min_recommend_value - 1)
            user_mgr.update_broadcaster_recommend_value_by_uid(uid, recommend_value)
        else:
            recommend_value = current_recommend_value + 1
            user_mgr.update_broadcaster_recommend_value_by_value(recommend_value, current_recommend_value)
            user_mgr.update_broadcaster_recommend_value_by_uid(uid, recommend_value)
    elif offset == -1:
        # 排名减1
        recommend_value = max(1, current_recommend_value - 1)
        user_mgr.update_broadcaster_recommend_value_by_value(recommend_value, current_recommend_value)
        user_mgr.update_broadcaster_recommend_value_by_uid(uid, recommend_value)
    else:
        return ajax.error_response('Invalid offset')

    # result = vchat_api_mgr.set_user_recommend_value(uid, recommend_value)
    # Log.info(f'Request api result: {result}')
    return ajax.success_response()


@gma_login_required
def api_unrecommend_user(request):
    """ 置底主播 """
    uid = int(request.POST['uid'].strip())
    # recommend_value = int(time.time())
    recommend_value = 10000

    # result = vchat_api_mgr.set_user_recommend_value(uid, recommend_value)
    # Log.info(f'Request api result: {result}')
    user_mgr.update_broadcaster_recommend_value_by_uid(uid, recommend_value)
    return ajax.success_response()


@gma_login_required
def api_cancel_recommend_user(request):
    """ 取消置顶推荐主播 """
    uid = int(request.POST['uid'].strip())
    recommend_value = 0

    # result = vchat_api_mgr.set_user_recommend_value(uid, recommend_value)
    # Log.info(f'Request api result: {result}')
    user_mgr.update_broadcaster_recommend_value_by_uid(uid, recommend_value)
    return ajax.success_response()


@gma_login_required
def api_ban_user(request):
    """ 冻结账号 """
    uid = int(request.POST['uid'].strip())

    user_mgr.ban_user(uid)
    result = vchat_api_mgr.user_logout(uid)
    Log.info(f'Request api result: {result}')
    return ajax.success_response()


@gma_login_required
def api_unban_user(request):
    """ 撤销冻结账号 """
    uid = int(request.POST['uid'].strip())

    user_mgr.unban_user(uid)
    return ajax.success_response()


@gma_login_required
def api_ban_user_device(request):
    """ 冻结设备 """
    uid = int(request.POST['uid'].strip())
    user = user_mgr.get_user_detail(uid)
    device_id = user['last_login_device']

    device_id = device_id.lower()
    if device_id in ['', 'null', 'unknown', '00000000-0000-0000-0000-000000000000']:
        return ajax.error_response('无法冻结该用户的设备！')

    user_mgr.ban_user_device(uid, device_id)
    result = vchat_api_mgr.user_logout(uid)
    Log.info(f'Request api result: {result}')
    return ajax.success_response()


@gma_login_required
def api_unban_user_device(request):
    """ 撤销冻结设备 """
    uid = int(request.POST['uid'].strip())
    user = user_mgr.get_user_detail(uid)
    device_id = user['last_login_device']

    user_mgr.unban_user_device(device_id)
    return ajax.success_response()


@gma_login_required
def api_ban_user_ip(request):
    """ 冻结IP """
    uid = int(request.POST['uid'].strip())
    user = user_mgr.get_user_detail(uid)
    ip = user['last_login_ip']

    user_mgr.ban_user_ip(uid, ip)
    result = vchat_api_mgr.user_logout(uid)
    Log.info(f'Request api result: {result}')
    return ajax.success_response()


@gma_login_required
def api_unban_user_ip(request):
    """ 撤销冻结设备 """
    uid = int(request.POST['uid'].strip())
    user = user_mgr.get_user_detail(uid)
    ip = user['last_login_ip']

    user_mgr.unban_user_ip(ip)
    return ajax.success_response()


@gma_login_required
def api_refresh_user_cache(request):
    """ 刷新用户缓存 """
    uid = int(request.POST['uid'].strip())

    result = vchat_api_mgr.refresh_user_cache(uid)
    Log.info(f'Request refresh user cache api result: {result}')
    return ajax.success_response()


@gma_login_required
def api_set_cast_price(request):
    """ 增加直播价格 """
    uid = request.POST['uid'].strip()
    price = request.POST['price'].strip()

    result = vchat_api_mgr.set_cast_price(uid, price)
    Log.info(f'Request api result: {result}')
    return ajax.success_response()


@gma_login_required
def api_set_caster_star(request):
    """ 增加直播星级 """
    uid = request.POST['uid'].strip()
    star = int(request.POST['star'].strip())

    result = vchat_api_mgr.set_caster_star(uid, star)
    Log.info(f'Request api result: {result}')
    return ajax.success_response()


@gma_login_required
def api_set_room_tag(request):
    """ 设置房间品类 """
    uid = request.POST['uid'].strip()
    tag_id = int(request.POST['tag_id'].strip())

    user_mgr.update_caster_room_tag(uid, tag_id)
    return ajax.success_response()


@gma_login_required
def api_create_guild(request):
    """ 创建公会 """
    guild_name = request.POST['guild_name'].strip()
    chief_uid = request.POST['chief_uid'].strip()

    # 判断用户的权限
    if not helpers.has_permission(request, gm_mgr.PERMISSION_GUILD_MANAGEMENT):
        return ajax.error_response(f'权限不足!')

    if not helpers.can_access_user(request, chief_uid):
        return ajax.error_response(f'无权访问用户"{chief_uid}"!')

    if guild_mgr.get_guild_by_name(guild_name) is not None:
        return ajax.error_response(f'公会名"{guild_name}"已存在!')

    if not user_mgr.is_valid_uid(chief_uid):
        return ajax.error_response(f'用户"{chief_uid}"的id无效!')

    if guild_mgr.get_guild_by_chief_uid(chief_uid) is not None:
        return ajax.error_response(f'用户"{chief_uid}"已经是另一个公会的会长!')

    # 创建公会
    guild_mgr.create_guild(guild_name, chief_uid)

    # 增加GM对公会的访问权限
    guild = guild_mgr.get_guild_by_chief_uid(chief_uid)
    if guild:
        guild_id = guild['id']
        gm_id = helpers.get_request_gm_id(request)
        gm_mgr.create_guild(gm_id, guild_id)

    return ajax.success_response()


@gma_login_required
def api_recruit_guild_members(request):
    """ 招募公会成员 """
    guild_id = request.POST['guild_id'].strip()
    uids = request.POST['uids']

    # 判断用户的权限
    if not helpers.can_access_guild(request, guild_id):
        return ajax.error_response('权限不足!')

    # 判断公会id是否合法
    guild = guild_mgr.get_guild_info(guild_id)
    if guild is None:
        return ajax.error_response(f'无效的公会id：{guild_id}')

    # 判断用户id是否合法
    uids = uids.split('\n')
    members = []
    for uid in uids:
        uid = uid.strip()
        if not uid:
            continue
        if not uid.isdigit():
            return ajax.error_response(f'无效的用户id：{uid}')

        uid = int(uid)
        if not user_mgr.is_valid_uid(uid):
            return ajax.error_response(f'无效的用户id：{uid}')
        if guild_mgr.get_user_guild_id(uid) is not None:
            return ajax.error_response(f'用户{uid}已经是公会成员了！')

        # 判断request是否有权限浏览uid
        if not helpers.can_access_user(request, uid):
            return ajax.error_response(f'无权访问id: {uid}')

        members.append(uid)

    if not members:
        return ajax.error_response(f'用户列表为空!')

    # 添加公会成员
    for uid in members:
        guild_mgr.add_guild_member(guild_id, uid)

    return ajax.success_response()


@gma_login_required
def api_leave_guild(request):
    """ 请离公会"""
    uid = request.POST['uid'].strip()

    # 判断用户的权限
    guild_id = guild_mgr.get_user_guild_id(uid)
    if not helpers.can_access_guild(request, guild_id):
        return ajax.error_response('权限不足!')

    guild_mgr.remove_guild_member(uid)
    return ajax.success_response()


@gma_login_required
def api_bind_guild_mobile(request):
    """ 绑定公会手机号码 """
    guild_id = request.POST['guild_id'].strip()
    mobile = request.POST['mobile'].strip()

    # 判断用户的权限
    if not helpers.can_access_guild(request, guild_id):
        return ajax.error_response('权限不足!')

    guild_mgr.bind_mobile(guild_id, mobile)
    return ajax.success_response()


@gma_login_required
def api_push_message(request):
    """ 给用户推送消息 """
    category = int(request.POST.get('category', '0').strip())
    uid = int(request.POST.get('uid', '0').strip())
    message = request.POST['message'].strip()
    apns_production = int(request.POST.get('apns_production', '1'))
    Log.info(f'Push message to user: uid={uid}, msg={message}, apns={apns_production}')

    openid = helpers.get_request_openid(request)
    gm_id = gm_mgr.get_gm_id(openid)

    if category == USER_CATEGORY_ALL_USERS:
        # 推送给所有用户
        user_count = user_mgr.get_total_user_count()
        comment = f'共推送给{user_count}个用户'
        message_id = radio_mgr.save_message(gm_id, category, uid, message, comment)
        extras = {
            'type': 'ActivityNotice',
            'message_id': message_id,
        }
        jpush_mgr.push_message_to_all_users(message, extras, apns_production)
        # 私信不能发送给所有用户
    else:
        if category == USER_CATEGORY_NONE:
            # 推送给单个用户
            uids = [str(uid)]
        elif category == USER_CATEGORY_ALL_PREMIUM_USERS:
            # 推送给所有付费用户
            users = user_mgr.get_all_premium_users()
            uids = [str(x['uid']) for x in users]
        elif category == USER_CATEGORY_ALL_CASTERS:
            # 推送给所有主播
            users = user_mgr.get_all_casters()
            uids = [str(x['uid']) for x in users]
        elif category == USER_CATEGORY_ALL_ONLINE_CASTERS:
            # 推送给所有在线主播
            users = user_mgr.get_all_online_casters()
            uids = [str(x['uid']) for x in users]
        elif category == USER_CATEGORY_TEST_USERS:
            # 推送给所有测试用户
            users = user_mgr.get_all_test_users()
            uids = [str(x['uid']) for x in users]
        else:
            return ajax.error_response('无效的推送类型')

        user_count = len(uids)
        comment = f'共推送给{user_count}个用户'
        message_id = radio_mgr.save_message(gm_id, category, uid, message, comment)
        extras = {
            'type': 'ActivityNotice',
            'message_id': message_id,
        }
        jpush_mgr.push_message_to_users(uids, message, extras, apns_production)
        # vchat_api_mgr.send_hx_message_to_users(','.join(uids), message)

    return ajax.success_response()


@gma_login_required
def api_agree_complaint(request):
    """ 接受用户举报 """
    cid = request.POST['cid'].strip()

    complaint_mgr.agree(cid)
    return ajax.success_response()


@gma_login_required
def api_reject_complaint(request):
    """ 拒绝用户举报 """
    cid = request.POST['cid'].strip()

    complaint_mgr.reject(cid)
    return ajax.success_response()


def api_login(request):
    """ 用户登录 """
    mobile = request.POST['mobile'].strip()
    sms_code = request.POST['sms_code'].strip()

    if not mobile:
        return ajax.error_response('无效的手机号码!')

    if not sms_code:
        return ajax.error_response('无效的验证码!')

    # 检测验证码是否合法
    if not sms_mgr.is_valid_sms_code(mobile, sms_code):
        return ajax.error_response('无效的验证码!')

    # 判断是否是GM账号
    gm = gm_mgr.get_gm_by_mobile(mobile)
    if gm is None:
        return ajax.error_response('无效的GM账号!')

    # 保存登录状态
    helpers.login(request, mobile)
    return ajax.success_response()


@gma_login_required
def api_logout(request):
    """ 用户登出 """
    helpers.logout(request)
    return ajax.success_response()


def api_fetch_smscode(request):
    """ 获取验证码 """
    mobile = request.POST['mobile'].strip()
    if not mobile:
        return ajax.error_response('手机号码不可以为空!')

    sms_code = ''.join([random.choice('0123456789') for _ in range(4)])
    success = sms_mgr.send_sms_code(mobile, sms_code)
    if not success:
        return ajax.error_response('验证码发送失败!')

    return ajax.success_response({}, '验证码已发送')


def api_archive_server_data(request):
    """ 归档服务器数据
        不需要登录.
    """
    err, data = usecases.api_archive_server_data(request)
    if err != ERROR_NO_ERROR:
        return ajax.error_response(err['message'], err['id'])
    return ajax.success_response(data)


@gma_login_required
def api_send_hx_message(request):
    """ 给用户发送私信 """
    uid = request.POST['uid'].strip()
    message = request.POST['message'].strip()

    result = vchat_api_mgr.send_hx_message(uid, message)
    user_mgr.save_private_message(120001, uid, message)
    return ajax.success_response()


@gma_login_required
def api_shutdown_channel(request):
    """ 关闭指定的频道 """
    channel_name = request.POST['channel_name'].strip()

    result = vchat_api_mgr.shutdown_channel(channel_name)
    return ajax.success_response()


@gma_login_required
def api_delete_guild(request):
    """ 删除公会 """
    guild_id = int(request.POST['guild_id'].strip())

    # 判断用户是否有权限删除指定的公会
    if not helpers.can_access_guild(request, guild_id):
        return ajax.error_response('权限不足!')

    guild_mgr.delete_guild(guild_id)
    return ajax.success_response()


@gma_login_required
def api_sterilize_app(request):
    """ 过滤应用 """
    app_id = int(request.POST['app_id'].strip())
    sterilize_type = int(request.POST['sterilize_type'].strip())

    app_mgr.update_app_sterilize_type(app_id, sterilize_type)
    return ajax.success_response()


@gma_login_required
def api_sterilize_channel(request):
    """ 过滤渠道 """
    channel_id = int(request.POST['channel_id'].strip())
    sterilize_type = int(request.POST['sterilize_type'].strip())

    app_mgr.update_channel_sterilize_type(channel_id, sterilize_type)
    return ajax.success_response()


@gma_login_required
def api_modify_caster_nickname(request):
    """ 修改主播的昵称 """
    uid = request.POST['uid'].strip()
    nickname = request.POST['nickname'].strip()

    vchat_api_mgr.modify_caster_nickname(uid, nickname)
    return ajax.success_response()


@gma_login_required
def api_modify_caster_signature(request):
    """ 修改主播的签名 """
    uid = request.POST['uid'].strip()
    signature = request.POST['signature'].strip()

    vchat_api_mgr.modify_caster_signature(uid, signature)
    return ajax.success_response()


@gma_login_required
def api_modify_caster_introduction(request):
    """ 修改主播的昵称 """
    uid = request.POST['uid'].strip()
    introduction = request.POST['introduction'].strip()

    vchat_api_mgr.modify_caster_introduction(uid, introduction)
    return ajax.success_response()


@gma_login_required
def api_get_qiniu_video_upload_token(request):
    """ 获取七牛视频的上传token """
    token = qiniu_util.get_upload_token(
        settings.QINIU_ACCESS_KEY,
        settings.QINIU_SECRET_KEY,
        settings.QINIU_VIDEO_BUCKET_NAME,
    )
    data = {
        'token': token,
    }
    return ajax.success_response(data)


@gma_login_required
def api_upload_video_for_caster(request):
    uid = request.POST['uid'].strip()
    video_url = request.POST['video_url'].strip()
    cover_url = video_url + '?vframe/png/offset/0'
    video_mgr.add_video_for_user(uid, cover_url, video_url)
    return ajax.success_response()


@gma_login_required
def api_refund_video_chat(request):
    liveid = int(request.POST['liveid'].strip())

    vchat_api_mgr.refund_video_chat(liveid)
    return ajax.success_response()


@gma_login_required
def api_video_to_moment(request):
    """ 将主播的短视频转为动态发送出去 """
    videos = video_mgr.get_verified_videos()
    random.shuffle(videos)
    count = 0
    for video in videos:
        uid = video['uid']
        video_url = video['video_url']
        ok = moment_mgr.create_video_moment(uid, video_url)
        if ok:
            count += 1

    data = {
        'count': count
    }
    return ajax.success_response(data)


@gma_login_required
def api_review_video_chat(request):
    """ 审核视频通话记录 """
    liveid = int(request.POST['liveid'].strip())
    call_mgr.set_call_log_review_status(liveid, 1)
    return ajax.success_response()


@gma_login_required
def api_unreview_video_chat(request):
    """ 取消视频通话记录的审核 """
    liveid = int(request.POST['liveid'].strip())
    call_mgr.set_call_log_review_status(liveid, 0)
    return ajax.success_response()


@gma_login_required
def api_review_private_message(request):
    """ 审核视频通话记录 """
    mid = int(request.POST['mid'].strip())
    message_mgr.set_log_review_status(mid, 1)
    return ajax.success_response()


@gma_login_required
def api_unreview_private_message(request):
    """ 取消视频通话记录的审核 """
    mid = int(request.POST['mid'].strip())
    message_mgr.set_log_review_status(mid, 0)
    return ajax.success_response()


@gma_login_required
def api_brief_data(request):
    """ 获取服务器简报 `"""
    today_begin_time, today_end_time = util.get_today_interval()

    context = helpers.build_context(request)
    del context['permissions']

    context['gm_name'] = helpers.get_request_gm_name(request)
    context['begin_time'] = today_begin_time
    context['end_time'] = today_end_time

    # 今日充值金额数量
    context['today_pay_amount'] = user_mgr.get_pay_amount(today_begin_time, today_end_time, request)
    # 今日累计新增用户数量
    context['today_new_user_count'] = user_mgr.get_new_user_count(today_begin_time, today_end_time, request=request)
    # 今日累计消耗钻石数量
    context['today_consume_amount'] = -1 * user_mgr.get_consume_amount(today_begin_time, today_end_time, request=request)

    # # 钻石数量监测
    # context['diamond_detail'] = pay_mgr.get_diamond_stat_detail()
    # 未读客服信息数量
    context['unread_customer_service_message_count'] = user_mgr.get_unread_message_count(120001)
    # 待审核的提现记录数量
    context['waiting_auth_withdraw_count'] = 0
    # 未处理的用户举报数量
    context['opened_complaint_count'] = complaint_mgr.get_complaint_records_count(AUTH_STATUS_WAITING)

    # 待审内容
    waiting_auth_user_count = user_mgr.get_waiting_auth_user_count_by_status(AUTH_STATUS_WAITING, request)
    context['waiting_auth_user_count'] = waiting_auth_user_count
    waiting_auth_video_count = video_mgr.get_video_count_by_auth_status(VIDEO_AUTH_STATUS_WAITING, request)
    context['waiting_auth_video_count'] = waiting_auth_video_count
    waiting_auth_photo_count = photo_mgr.get_photo_count_by_auth_status(PHOTO_AUTH_STATUS_WAITING, request)
    context['waiting_auth_photo_count'] = waiting_auth_photo_count
    # 待审核的主播资料数量
    waiting_auth_profile_count = profile_mgr.get_profile_count_by_auth_status(PROFILE_AUTH_STATUS_WAITING, request)
    context['waiting_auth_profile_count'] = waiting_auth_profile_count
    # 待审核的主播动态数量
    waiting_auth_moment_count = moment_mgr.get_moment_count_by_auth_status(AUTH_STATUS_WAITING, request)
    context['waiting_auth_moment_count'] = waiting_auth_moment_count
    # 累计待审核数量
    context['waiting_auth_count'] = waiting_auth_user_count + waiting_auth_video_count + waiting_auth_photo_count + \
        waiting_auth_profile_count + waiting_auth_moment_count

    context['arpu'] = round(context['today_pay_amount']/context['today_new_user_count'] if context['today_new_user_count'] > 0 else 0, 2)
    return ajax.success_response(context)


@gma_login_required
def api_enable_banner(request):
    """ 启用banner """
    banner_id = int(request.POST['banner_id'].strip())
    ok = banner_mgr.enable_banner(banner_id)
    if not ok:
        return ajax.error_response('启用失败!')
    return ajax.success_response(None, '启用成功!')


@gma_login_required
def api_disable_banner(request):
    """ 启用banner """
    banner_id = int(request.POST['banner_id'].strip())
    ok = banner_mgr.disable_banner(banner_id)
    if not ok:
        return ajax.error_response('启用失败!')
    return ajax.success_response(None, '禁用成功!')


@gma_login_required
def api_edit_banner(request):
    """ 编辑banner """
    banner_id = int(request.POST['banner_id'].strip())
    banner_name = request.POST['banner_name'].strip()
    banner_orderno = int(request.POST['banner_orderno'].strip())
    banner_image_url = request.POST['banner_image_url'].strip()
    banner_link_url = request.POST['banner_link_url'].strip()

    if not banner_image_url:
        return ajax.error_response('图片地址不可以为空!')

    ok = banner_mgr.edit_banner(banner_id, banner_name, banner_orderno, banner_image_url, banner_link_url)
    if not ok:
        return ajax.error_response('修改失败!')
    return ajax.success_response(None, '修改成功!')


@gma_login_required
def api_get_banner_list(request):
    """ 请求banner列表 """
    banner_type = int(request.POST['banner_type'].strip())
    banners = banner_mgr.get_banner_list(banner_type)
    return ajax.success_response(banners)


@gma_login_required
def api_new_banner(request):
    """ 添加新的banner """
    bundle_id = request.POST['bundle_id'].strip()
    banner_type = int(request.POST['banner_type'].strip())
    name = request.POST['name'].strip()
    orderno = int(request.POST['orderno'].strip())
    image_url = request.POST['image_url'].strip()
    link_url = request.POST['link_url'].strip()
    Log.info(f'Add new banner: bundle_id={bundle_id}, type={banner_type}, name={name}, orderno={orderno}, image={image_url}, link={link_url}')

    if not bundle_id:
        return ajax.error_response('Bundle id不可以为空!')
    if not name:
        return ajax.error_response('名称不可以为空!')
    if not image_url:
        return ajax.error_response('图片地址不可以为空!')
    if not link_url:
        return ajax.error_response('链接地址不可以为空!')

    ok = banner_mgr.new_banner(bundle_id, banner_type, name, orderno, image_url, link_url)
    if not ok:
        return ajax.error_response('添加失败!')

    return ajax.success_response()


@gma_login_required
def api_enable_gift(request):
    """ 启用礼物 """
    gift_id = int(request.POST['gift_id'].strip())
    ok = gift_mgr.enable_gift(gift_id)
    if not ok:
        return ajax.error_response('启用失败!')
    return ajax.success_response(None, '启用成功!')


@gma_login_required
def api_disable_gift(request):
    """ 停用礼物 """
    gift_id = int(request.POST['gift_id'].strip())
    ok = gift_mgr.disable_gift(gift_id)
    if not ok:
        return ajax.error_response('启用失败!')
    return ajax.success_response(None, '禁用成功!')


@gma_login_required
def api_edit_gift(request):
    """ 编辑礼物 """
    gift_id = int(request.POST['gift_id'].strip())
    # gift_bundle_id = request.POST['gift_bundle_id'].strip()
    gift_name = request.POST['gift_name'].strip()
    gift_price = int(request.POST['gift_price'].strip())
    gift_orderno = int(request.POST['gift_orderno'].strip())
    gift_icon = request.POST['gift_icon'].strip()
    gift_resource = request.POST['gift_resource'].strip()

    if not gift_icon:
        return ajax.error_response('图标地址不可以为空!')
    if not gift_resource:
        return ajax.error_response('资源地址不可以为空!')

    ok = gift_mgr.edit_gift(gift_id, gift_name, gift_price, gift_icon, gift_resource, gift_orderno)
    if not ok:
        return ajax.error_response('修改失败!')
    return ajax.success_response(None, '修改成功!')


@gma_login_required
def api_get_gift_list(request):
    """ 请求礼物列表 """
    gifts = gift_mgr.get_gift_list()
    return ajax.success_response(gifts)


@gma_login_required
def api_new_gift(request):
    """ 添加新的礼物 """
    name = request.POST['name'].strip()
    price = int(request.POST['price'].strip())
    orderno = int(request.POST['orderno'].strip())
    icon = request.POST['icon'].strip()
    resource = request.POST['resource'].strip()
    Log.info(f'Add new gift: name={name}, orderno={orderno}, icon={icon}, resource={resource}')

    if not name:
        return ajax.error_response('名称不可以为空!')
    if not icon:
        return ajax.error_response('图片地址不可以为空!')
    if not resource:
        return ajax.error_response('资源地址不可以为空!')

    ok = gift_mgr.new_gift(name, price, icon, resource, orderno)
    if not ok:
        return ajax.error_response('添加失败!')

    return ajax.success_response()


@gma_login_required
def api_get_gift_category_list(request):
    """ 请求礼物分类列表 """
    categories = gift_mgr.get_gift_category_list()
    gifts_count = gift_mgr.get_gift_count_group_by_category()
    for category in categories:
        category['gift_count'] = gifts_count.get(category['category_id'], 0)

    return ajax.success_response(categories)


@gma_login_required
def api_new_gift_category(request):
    """ 添加新的礼物分类 """
    category_id = int(request.POST['category_id'].strip())
    category_name = request.POST['category_name'].strip()
    orderno = int(request.POST['orderno'].strip())
    Log.info(f'Add new gift category: category_id={category_id}, name={category_name}, orderno={orderno}')

    if not category_name:
        return ajax.error_response('分类名称不可以为空!')

    ok = gift_mgr.new_gift_category(category_id, category_name, orderno)
    if not ok:
        return ajax.error_response('添加失败!')

    return ajax.success_response()


@gma_login_required
def api_enable_gift_category(request):
    """ 启用礼物分类 """
    gift_category_id = int(request.POST['gift_category_id'].strip())
    ok = gift_mgr.enable_gift_category(gift_category_id)
    if not ok:
        return ajax.error_response('启用失败!')
    return ajax.success_response(None, '启用成功!')


@gma_login_required
def api_disable_gift_category(request):
    """ 停用礼物分类 """
    gift_category_id = int(request.POST['gift_category_id'].strip())
    ok = gift_mgr.disable_gift_category(gift_category_id)
    if not ok:
        return ajax.error_response('启用失败!')
    return ajax.success_response(None, '禁用成功!')


@gma_login_required
def api_edit_gift_category(request):
    """ 编辑礼物分类 """
    category_id = int(request.POST['category_id'].strip())
    category_name = request.POST['category_name'].strip()
    category_orderno = int(request.POST['category_orderno'].strip())

    if not category_id:
        return ajax.error_response('分类id不可以为空!')
    if not category_name:
        return ajax.error_response('分类名称不可以为空!')

    ok = gift_mgr.edit_gift_category(category_id, category_name, category_orderno)
    if not ok:
        return ajax.error_response('修改失败!')
    return ajax.success_response(None, '修改成功!')


@gma_login_required
def api_get_online_user_count(request):
    """ 请求在线的用户数 """
    data = {
        'online_user_count': 7,
    }
    return ajax.success_response(data)


@gma_login_required
def api_recommend_room(request):
    """ 推荐/取消推荐房间 """
    uid = int(request.POST['uid'].strip())
    allowed = int(request.POST['allowed'].strip())
    ok = user_mgr.recommend_room(uid, allowed)
    if not ok:
        return ajax.error_response('设置失败!')

    return ajax.success_response()


if __name__ == '__main__':
    print('ok')
